package com.newtouch.bxzs.database.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.*;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.PinYinUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.database.mapper.*;
import com.newtouch.bxzs.database.model.bo.*;
import com.newtouch.bxzs.database.model.vo.*;
import com.newtouch.bxzs.database.service.CooperationCompanyService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 合作公司管理的Service接口的实现类
 *
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/20 17:26</td>
 * <td>田尚柱</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author 田尚柱
 * @version 1.0.0
 */

@Service
public class CooperationCompanyServiceImpl implements CooperationCompanyService {

    @Resource
    private CooperationCompanyMapper cooperationCompanyMapper;

    @Resource
    private CooperationCompanyParameterMapper cooperationCompanyParameterMapper;

    @Resource
    private CooperationUserMapper cooperationUserMapper;

    @Resource
    private CooperationCompanyOrganizationMapper cooperationCompanyOrganizationMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 静态变量：日志
     */
    private static final Log logger = LogFactory.getLog(CooperationCompanyServiceImpl.class);

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#getCooperationCompanyList(com.newtouch.bxzs.database.model.vo.CooperationCompanyVO)
     */
    @Override
    public IPage<CooperationCompanyBO> getCooperationCompanyList(CooperationCompanyVO cooperationCompanyVO) {
        if (cooperationCompanyVO == null || cooperationCompanyVO.getCurrentPage() == null || cooperationCompanyVO.getPageSize() == null) {
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /* 拿到当前页和每页数量*/
        Page<CooperationCompany> cooperationCompanyPage = new Page<>(cooperationCompanyVO.getCurrentPage(), cooperationCompanyVO.getPageSize());
        //实例化QueryWrapper
        QueryWrapper<CooperationCompany> query = new QueryWrapper<>();
        if (!StringUtils.isEmpty(cooperationCompanyVO.getCooperationCompanyName())) {
            /*根据合作公司名称查询*/
            query.like("COOPERATION_COMPANY_NAME", cooperationCompanyVO.getCooperationCompanyName());
        }
        if (!StringUtils.isEmpty(cooperationCompanyVO.getEnableFlag())) {
            /*查询启用或者禁用的合作公司*/
            query.eq("IS_ENABLE", cooperationCompanyVO.getEnableFlag());
        }
        /*选择排序顺序（按合作公司名称全拼排序）*/
        query.orderByAsc("COOPERATION_COMPANY_NAME_FULL_SPELLING");
        /* 通过输入条件查询*/
        IPage<CooperationCompany> iPage = cooperationCompanyMapper.selectPage(cooperationCompanyPage, query);
        if (iPage == null || CollectionUtil.isEmpty(iPage.getRecords())) {
            return null;
        }
        IPage<CooperationCompanyBO> boiPage = new Page<>();
        // 设置iPage*/
        boiPage.setRecords(EntityToBeanUtils.copyBean(iPage.getRecords(), CooperationCompanyBO.class));
        boiPage.setTotal(iPage.getTotal());
        boiPage.setSize(iPage.getSize());
        boiPage.setPages(iPage.getPages());
        boiPage.setCurrent(iPage.getCurrent());
        return boiPage;
    }

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#modifyCooperationCompany(com.newtouch.bxzs.database.model.vo.CooperationCompanyModifyVO)
     */
    @Override
    public String modifyCooperationCompany(CooperationCompanyModifyVO cooperationCompanyModifyVO) {
        if (cooperationCompanyModifyVO == null || StringUtils.isEmpty(cooperationCompanyModifyVO.getCooperationCompanyName()) ||
                StringUtils.isEmpty(cooperationCompanyModifyVO.getCooperationCompanyTelephone()) ||
                StringUtils.isEmpty(cooperationCompanyModifyVO.getUnifiedSocialCreditCode())) {
            logger.error("必传项为空！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        List<CooperationCompanyParameterVO> cooperationCompanyParameterVOList = cooperationCompanyModifyVO.getCooperationCompanyParameterVOList();
        if(!CollectionUtil.isEmpty(cooperationCompanyParameterVOList)){
            for (CooperationCompanyParameterVO cooperationCompanyParameterVO : cooperationCompanyParameterVOList) {
                //验证网址正则
                String value = cooperationCompanyParameterVO.getCooperationCompanyParameterValue();
                if(!StringUtils.isEmpty(value)){
                    if(!value.matches("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]$")){
                        throw new BaseException(BaseErrorEnum.REQUEST_NETWORK_PARAMETER_ERROR);
                    }
                }
            }
        }
        List<CooperationCompany> cooperationCompanies = cooperationCompanyMapper.selectList(null);
        for (CooperationCompany cooperationCompany : cooperationCompanies) {
            //信用代码和名称不能重复
            if (cooperationCompany.getUnifiedSocialCreditCode().equals(cooperationCompanyModifyVO.getUnifiedSocialCreditCode()) ||
                    cooperationCompany.getCooperationCompanyName().equals(cooperationCompanyModifyVO.getCooperationCompanyName())) {
                if (!StringUtils.isEmpty(cooperationCompanyModifyVO.getCooperationCompanyId())
                        && cooperationCompanyModifyVO.getCooperationCompanyId().equals(cooperationCompany.getCooperationCompanyId())) {
                    //正在修改这个合作公司，不抛异常
                    break;
                }
                throw new BaseException(BaseErrorEnum.DATA_EXISTS);
            }
        }
        /* 实例化CooperationCompany*/
        CooperationCompany cooperationCompany = new CooperationCompany();
        /* 使用工具直接进行实体与BO的复制转换，前面是来源，后面是目标*/
        BeanUtil.copyProperties(cooperationCompanyModifyVO, cooperationCompany);
        Date date = new Date();
        /*设置合作公司的拼音*/
        cooperationCompany.setCooperationCompanyNameFullSpelling(PinYinUtils.toFirstChar(cooperationCompany.getCooperationCompanyName()).replaceAll("[^a-z^A-Z]", ""));
        cooperationCompany.setCooperationCompanyCode(PinYinUtils.toFirstChar(cooperationCompany.getCooperationCompanyName()).replaceAll("[^a-z^A-Z]", ""));
        /*如果CooperationCompanyId为空，新增合作公司 */
        if (StringUtils.isEmpty(cooperationCompany.getCooperationCompanyId())) {
            cooperationCompany.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            cooperationCompany.setCreateTime(date);
            cooperationCompany.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            cooperationCompany.setUpdateTime(date);
            if (StringUtils.isEmpty(cooperationCompany.getEnableFlag())) {
                cooperationCompany.setEnableFlag(false);
            }
            cooperationCompany.setDeleteFlag(false);
            cooperationCompanyMapper.insert(cooperationCompany);
            /* 新增合作公司参数*/
        } else {
            if (cooperationCompanyMapper.selectById(cooperationCompany.getCooperationCompanyId()).getEnableFlag()) {
                logger.error("只能修改未启用的合作公司");
                throw new BaseException(BaseErrorEnum.ENABLE_USE);
            }
            cooperationCompany.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            cooperationCompany.setUpdateTime(date);
            /*如果CooperationCompanyId不为空，修改合作公司 */
            cooperationCompanyMapper.updateById(cooperationCompany);
            /* 再修改合作公司参数*/
            if (!CollectionUtils.isEmpty(cooperationCompanyParameterVOList)) {
                /* 先删除以前的数据，再新增*/
                //实例化QueryWrapper
                QueryWrapper<CooperationCompanyParameter> query = new QueryWrapper<>();
                /*根据数据字典id作为条件*/
                query.eq("COOPERATION_COMPANY_ID", cooperationCompany.getCooperationCompanyId());
                /* 删除*/
                cooperationCompanyParameterMapper.delete(query);
                /* 新增合作公司参数*/
            }
        }
        /* 新增合作公司参数*/
        /* 判断输入的合作公司参数列表是否为空*/
        if (!CollectionUtils.isEmpty(cooperationCompanyParameterVOList)) {
            /* 复制合作公司参数集合*/
            List<CooperationCompanyParameter> cooperationCompanyParameterList = EntityToBeanUtils.copyBean(cooperationCompanyParameterVOList, CooperationCompanyParameter.class);
            /* 循环集合设置各种参数*/
            for (CooperationCompanyParameter cooperationCompanyParameter : cooperationCompanyParameterList) {
                cooperationCompanyParameter.setCooperationCompanyId(cooperationCompany.getCooperationCompanyId());
                cooperationCompanyParameter.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
                cooperationCompanyParameter.setCreateTime(date);
                cooperationCompanyParameter.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
                cooperationCompanyParameter.setUpdateTime(date);
            }
            cooperationCompanyParameterMapper.insertCooperationCompanyParameter(cooperationCompanyParameterList);
        }
        return "新增或修改合作公司成功";
    }

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#getCooperationCompanyDetail(java.lang.String)
     */
    @Override
    public CooperationCompanyDetailBO getCooperationCompanyDetail(String cooperationCompanyId) {
        if (StringUtils.isEmpty(cooperationCompanyId)) {
            logger.error("合作公司id输入为空");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*通过id查询合作公司*/
        CooperationCompany cooperationCompany = cooperationCompanyMapper.selectById(cooperationCompanyId);
        if (BeanUtil.isEmpty(cooperationCompany)) {
            logger.error("合作公司id输入错误");
            throw new BaseException(BaseErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        /*实例化CooperationCompanyDetailBO*/
        CooperationCompanyDetailBO cooperationCompanyBO = new CooperationCompanyDetailBO();
        /* 使用工具直接进行实体与BO的复制转换，前面是来源，后面是目标*/
        BeanUtil.copyProperties(cooperationCompany, cooperationCompanyBO);
        //实例化QueryWrapper
        QueryWrapper<CooperationCompanyParameter> query = new QueryWrapper<>();
        /*根据数据字典id查询,合作公司参数*/
        query.eq("COOPERATION_COMPANY_ID", cooperationCompanyId);
        List<CooperationCompanyParameter> cooperationCompanyParameters = cooperationCompanyParameterMapper.selectList(query);
        cooperationCompanyBO.setCooperationCompanyParameterBOList(EntityToBeanUtils.copyBean(cooperationCompanyParameters, CooperationCompanyParameterBO.class));
        User user = userMapper.selectById(cooperationCompany.getCreateUserId());
        cooperationCompanyBO.setCreateUserName(BeanUtil.isEmpty(user) ? "" : user.getUserName());
        return cooperationCompanyBO;
    }

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#changeCooperationCompanyStatus(com.newtouch.bxzs.database.model.vo.CooperationCompanyChangeVO)
     */
    @Override
    public String changeCooperationCompanyStatus(CooperationCompanyChangeVO cooperationCompanyChangeVO) {
        /* 判断CooperationCompanyId是否为空  || 判断enableFlag是否为空 */
        if (cooperationCompanyChangeVO == null || StringUtils.isEmpty(cooperationCompanyChangeVO.getCooperationCompanyId()) || StringUtils.isEmpty(cooperationCompanyChangeVO.getEnableFlag())) {
            logger.error("修改状态输入异常");
            throw new BaseException(BaseErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        /* 实例化QueryWrapper */
        QueryWrapper<CooperationCompany> query = new QueryWrapper<>();
        /* 实例化CooperationCompany */
        CooperationCompany dataDictionaryEntry = new CooperationCompany();
        /* 设置CooperationCompanyId为sql条件*/
        query.eq("COOPERATION_COMPANY_ID", cooperationCompanyChangeVO.getCooperationCompanyId());
        /* 设置状态，修改人，和修改时间*/
        dataDictionaryEntry.setEnableFlag(cooperationCompanyChangeVO.getEnableFlag());
        dataDictionaryEntry.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        dataDictionaryEntry.setUpdateTime(new Date());
        /* 修改启用禁用状态*/
        cooperationCompanyMapper.update(dataDictionaryEntry, query);
        return "启用/禁用合作公司成功";
    }

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#getInsuranceCompanyEnabled(com.newtouch.bxzs.database.model.vo.InsuranceCompanyVO)
     */
    @Override
    public InsuranceCompanyTotalBO getInsuranceCompanyEnabled(InsuranceCompanyVO insuranceCompanyVO) {
        if (insuranceCompanyVO == null) {
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        HashMap<String, List<InsuranceCompanyBO>> hashMap = new LinkedHashMap<>();
        //实例化QueryWrapper
        QueryWrapper<CooperationCompany> query = new QueryWrapper<>();
        if (!StringUtils.isEmpty(insuranceCompanyVO.getInsuranceCompanyName())) {
            query.like("COOPERATION_COMPANY_NAME", insuranceCompanyVO.getInsuranceCompanyName());
        }
        query.eq("IS_ENABLE", true);
        /*选择排序顺序（按合作公司名称全拼排序）*/
        query.orderByAsc("COOPERATION_COMPANY_NAME_FULL_SPELLING");
        List<InsuranceCompanyBO> insuranceCompanyBOList = EntityToBeanUtils.copyBean(cooperationCompanyMapper.selectList(query), InsuranceCompanyBO.class);
        InsuranceCompanyTotalBO insuranceCompanyTotalBO = new InsuranceCompanyTotalBO();
        if (CollectionUtils.isEmpty(insuranceCompanyBOList)) {
            if (!StringUtils.isEmpty(insuranceCompanyVO.getInsuranceCompanyName())) {
                insuranceCompanyTotalBO.setTotal(0);
                insuranceCompanyTotalBO.setInsuranceCompanyBOList(null);
                return insuranceCompanyTotalBO;
            }
            //没有已启用的合作公司
            throw new BaseException(BaseErrorEnum.NOT_FOUND);
        }
        // 判断是否需要首字母
        if (insuranceCompanyVO.getFirstFlag()) {
            //带首字母的保险公司列表
            //公司名称拼音首字母作为key
            for (InsuranceCompanyBO insBO : insuranceCompanyBOList) {
                String nameFullSpelling = insBO.getCooperationCompanyNameFullSpelling();
                //如果全拼为空，调拼音工具类，再次获取全拼
                if(StringUtils.isEmpty(nameFullSpelling)){
                    String name = insBO.getCooperationCompanyName();
                    //如果名称为空，数据异常，抛异常
                    if(StringUtils.isEmpty(name)){
                        throw new BaseException(BaseErrorEnum.NOT_FOUND);
                    }
                    nameFullSpelling = PinYinUtils.toFirstChar(name);
                }
                String charFirst = nameFullSpelling.charAt(0) + "";
                String first = charFirst.toUpperCase();
                List<InsuranceCompanyBO> list = hashMap.get(first);
                if (CollectionUtil.isEmpty(list)) {
                    list = new ArrayList<>();
                }
                list.add(insBO);
                hashMap.put(first, list);
            }
        } else {
            //不带首字母的保险公司列表
            hashMap.put("insuranceCompanyBOList", insuranceCompanyBOList);
        }
        //设置总条数
        insuranceCompanyTotalBO.setTotal(insuranceCompanyBOList.size());
        insuranceCompanyTotalBO.setInsuranceCompanyBOList(hashMap);
        return insuranceCompanyTotalBO;
    }

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#getCompanyByCode(java.util.List)
     */
    @Override
    public CooperationCompanyListBO getCompanyByCode(List<String> codeList) {
        QueryWrapper<CooperationCompany> query = new QueryWrapper<>();
        query.eq("IS_ENABLE", true);
        if (!CollectionUtils.isEmpty(codeList)) {
            //统一社会信用代码集合输入不为空,根据code查询
            query.in("UNIFIED_SOCIAL_CREDIT_CODE", codeList);
        }
        List<CooperationCompanyBO> cooperationCompanyBOList = EntityToBeanUtils.copyBean(cooperationCompanyMapper.selectList(query), CooperationCompanyBO.class);
        if(CollectionUtils.isEmpty(cooperationCompanyBOList)){
            return null;
        }
        CooperationCompanyListBO cooperationCompanyListBO = new CooperationCompanyListBO();
        cooperationCompanyListBO.setCooperationCompanyBOList(cooperationCompanyBOList);
        return cooperationCompanyListBO;
    }

    /**
     * 通过机构编码，获取合作公司机构下的用户
     *
     * @param cooperationCompanyAllUserVO 合作公司用户VO
     * @return 合作公司机构下的用户
     */
    @Override
    public CooperationUserTotalBO getCooperationUserFirstByCode(CooperationCompanyAllUserVO cooperationCompanyAllUserVO) {
        List<CooperationCompanyCodeUserBO> list = getCooperationCompanyUserByCode(cooperationCompanyAllUserVO);
        HashMap<String, List<CooperationCompanyCodeUserBO>> hashMap = new LinkedHashMap<>();
        CooperationUserTotalBO cooperationUserTotalBO = new CooperationUserTotalBO();
        if (CollectionUtils.isEmpty(list)) {
            if (!BeanUtil.isEmpty(cooperationCompanyAllUserVO.getCooperationCompanyUserName())) {
                cooperationUserTotalBO.setTotal(0);
                cooperationUserTotalBO.setCooperationUserBOList(null);
                return cooperationUserTotalBO;
            }
            logger.error("合作公司用户");
            throw new BaseException(BaseErrorEnum.NOT_FOUND);
        }
        //名字拼音首字母作为key
        for (CooperationCompanyCodeUserBO userBO : list) {
            String cooperationCompanyUserName = userBO.getCooperationCompanyUserName();
            //如果名称为空，数据异常，抛异常
            if(StringUtils.isEmpty(cooperationCompanyUserName)){
                throw new BaseException(BaseErrorEnum.NOT_FOUND);
            }
            String charFirst = PinYinUtils.toFirstChar(cooperationCompanyUserName).charAt(0) + "";
            String first = charFirst.toUpperCase();
            List<CooperationCompanyCodeUserBO> listBO = hashMap.get(first);
            if (CollectionUtil.isEmpty(listBO)) {
                listBO = new ArrayList<>();
            }
            listBO.add(userBO);
            hashMap.put(first, listBO);
        }
        cooperationUserTotalBO.setTotal(list.size());
        cooperationUserTotalBO.setCooperationUserBOList(hashMap);
        //获取带首字母的合作公司用户成功
        return cooperationUserTotalBO;
    }

    /**
     * (non-Javadoc)
     *
     * @see com.newtouch.bxzs.database.service.CooperationCompanyService#getCooperationCompanyUserByCode(com.newtouch.bxzs.database.model.vo.CooperationCompanyAllUserVO)
     */
    @Override
    public List<CooperationCompanyCodeUserBO> getCooperationCompanyUserByCode(CooperationCompanyAllUserVO cooperationCompanyAllUserVO) {
        if (cooperationCompanyAllUserVO == null || StringUtils.isEmpty(cooperationCompanyAllUserVO.getCooperationCompanyOrganizationCode())) {
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        QueryWrapper<CooperationCompanyUser> query = new QueryWrapper<>();
        //按照拼音排序
        query.orderByAsc("CONVERT ( COOPERATION_COMPANY_USER_NAME USING gbk ) COLLATE gbk_chinese_ci");
        // 通过名字查询
        if (!BeanUtil.isEmpty(cooperationCompanyAllUserVO.getCooperationCompanyUserName())) {
            query.like("COOPERATION_COMPANY_USER_NAME", cooperationCompanyAllUserVO.getCooperationCompanyUserName());
        }
        query.eq("COOPERATION_COMPANY_USER_ORGANIZATION_CODE", cooperationCompanyAllUserVO.getCooperationCompanyOrganizationCode());
        List<CooperationCompanyCodeUserBO> list = EntityToBeanUtils.copyBean(cooperationUserMapper.selectList(query), CooperationCompanyCodeUserBO.class);
        //统一社会信用代码
        QueryWrapper<CooperationCompanyOrganization> organizationQuery = new QueryWrapper<>();
        organizationQuery.eq("COOPERATION_COMPANY_ORGANIZATION_CODE",cooperationCompanyAllUserVO.getCooperationCompanyOrganizationCode());
        String dataSource = cooperationCompanyOrganizationMapper.selectOne(organizationQuery).getDataSource();
        for (CooperationCompanyCodeUserBO userBO : list) {
            userBO.setDataSource(dataSource);
        }
        return list;
    }
}
